package com.foodlocker.courier;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Instrumentation;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.foodlocker.bean.Courier;
import com.foodlocker.common.CommonFunction;
import com.foodlocker.common.Constant;
import com.foodlocker.common.TransPasswordUtil;
import com.foodlocker.common.UniversalHttpPost;
import com.foodlocker.common.UniversalKeyboard;
import com.foodlocker.machine.MainActivity;
import com.foodlocker.machine.R;
import com.foodlocker.maintenance.MaintenancerLoginAct;

public class CourierLoginAct extends Activity{

	Button login;
	EditText telnum,secret;
	TextView  result,title;
	ProgressBar prgs;
	Button back;
	View.OnClickListener myOnClickListener;
//	LinearLayout lt_mother;
	UniversalKeyboard keyboard;
	View.OnFocusChangeListener focusListener;
	
	String AFFAIR_COURIER_LOGIN="courierLogin";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_stufflogin);
		init_listener();
		login=(Button) findViewById(R.id.btn_login_actstufflogin);
		result=(TextView) findViewById(R.id.tv_result__actstufflogin);
		telnum= (EditText) findViewById(R.id.et_telnum_actstufflogin);
		secret= (EditText) findViewById(R.id.et_secret_actstufflogin);
		prgs= (ProgressBar) findViewById(R.id.prgs_actstufflogin);	
		title=(TextView) findViewById(R.id.tv_title_actstufflogin);
		login.setOnClickListener(myOnClickListener);
		
		// lt_mother= (LinearLayout) findViewById(R.id.lt_mother_actmachinelogin);
		keyboard= new UniversalKeyboard(this,this,R.id.keyboard_actstufflogin);
		keyboard.showKeyboard();
		keyboard.setEditText(telnum);
		prgs.setVisibility(View.GONE);					
		result.setVisibility(View.GONE);	
		telnum.setOnFocusChangeListener(focusListener);
		secret.setOnFocusChangeListener(focusListener);		
	
		back= (Button) findViewById(R.id.btn_back_actstufflogin);
		back.setOnClickListener( new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				new Thread () { 
					public void run () { 
					try { 									
					Instrumentation inst= new Instrumentation(); 
					inst.sendKeyDownUpSync(KeyEvent. KEYCODE_BACK); 
					} catch(Exception e) { 
					e.printStackTrace(); 
					         } 
					  } 
					}.start();	
			}
		});
		
	}
    
	 
	private void init_listener(){
		
		focusListener= new View.OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if(hasFocus==true){
					if(v==telnum){
						keyboard.setEditText(telnum);
					}
					if(v==secret){
						keyboard.setEditText(secret);
					}
				}
				
			}
		};
		myOnClickListener= new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				if(v==login){
					JSONObject courierJO = new JSONObject();
					if( telnum.getText().toString().length()!=11){
						 new AlertDialog.Builder(CourierLoginAct.this).setTitle("输入错误提示")
						 .setMessage("电话11位数").setPositiveButton("确定", null).show();
						return; 
						}else{
						courierJO.put(Courier.TELNUM, telnum.getText().toString());
						    }
					String ciperText="";
					if( !CommonFunction.isNumeric(secret.getText().toString())||secret.getText().toString().isEmpty()){
						 new AlertDialog.Builder(CourierLoginAct.this).setTitle("输入错误提示")
						 .setMessage("密码必须全为数字,且不能为空").setPositiveButton("确定", null).show();
						return;
						 
						}else{
							try { ciperText =TransPasswordUtil.encrypt(secret.getText().toString());} catch (Exception e) {e.printStackTrace(); }
					     	courierJO.put(Courier.SECRET, ciperText);
						    }
		
					
					    prgs.setVisibility(View.VISIBLE);					
						result.setVisibility(View.VISIBLE);		
						 result.setText("登陆中，请稍后");
						 login.setClickable(false);
				    //     lt_mother.setFocusable(false);
						String[] params= new String[5];
			            params[0]=Constant.BaseUrl+Constant.MachineUrl;
		                params[1]=AFFAIR_COURIER_LOGIN; //PostCod
           
			               JSONObject jsonData=new JSONObject();	
			               jsonData.put("courier", courierJO.toString());	
			               jsonData.put("machine", Constant.machineJO.toString());			  
			                params[2]=jsonData.toString();
		                 new HttpPostTask().execute(params);
					}
					
				}
	
		};
	}
	

 
  class HttpPostTask extends android.os.AsyncTask<String,String,Map<String,Object>>{

		

		@Override
		protected Map<String,Object> doInBackground(String... params) {
			// TODO Auto-generated method stub
			 Map<String,Object> map = new HashMap<String ,Object>();		
		  map =	UniversalHttpPost.doPost(params);	             
			return map;
		}
		
		@Override
		protected void onPostExecute(Map<String,Object> map) {
				
			 System.out.println("-----------onPostExecute()--------------");
			 prgs.setVisibility(View.GONE);				
			 result.setVisibility(View.GONE);						
				 login.setClickable(true);
			//	 lt_mother.setFocusable(true);
			 String PostResult=(String) map.get("PostResult");		 
			 boolean networkstate=(Boolean) map.get("PostState");
			 if(!networkstate){
				 CommonFunction.alert(CourierLoginAct.this, "失败", "无网络连接");return;
		      
			}
			//	Toast.makeText(CourierLoginAct.this, "服务器返回数据为"+PostResult, Toast.LENGTH_SHORT).show();
			    JSONObject json = null;
			    int resultCode=-1;
				String resultInfo="";
				String affair="";				
				JSONObject jo;
				try{
			     json= JSONObject.fromObject(PostResult);
			     resultCode=json.getInt("resultCode");
			     resultInfo=json.getString("resultInfo");	
			     affair =json.getString("affair");	
			     jo= json.getJSONObject("jo");
				}catch(JSONException e){
					 CommonFunction.alert(CourierLoginAct.this, "失败", "数据解析错误");return;
				}
				
				if(resultCode==1){ 
					CommonFunction.alert(CourierLoginAct.this, "失败", resultInfo);return;
			    	     }
				 if(resultCode==2){ //成功
					if(affair.equals(AFFAIR_COURIER_LOGIN)){
						Constant.courierJO= jo.getJSONObject("courier");
						Constant.current_timeFlag=jo.getInt("timeFlag");
						MainActivity.StaffLoginCode="";
						 Intent intent= new Intent(CourierLoginAct.this, TakebackAct.class);
         			      startActivity(intent);
         			      CourierLoginAct.this.finish();
					}
					
				 }
				
			
		} //onPostExecute
	} //AsyncTask
}
